<template>
  <el-row :gutter="20">
    <el-col :span="14">
      <el-card>
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="6"><div class="grid-content ">{{ getText('changlanuage') }}</div></el-col>
          <el-col :span="6">
            <el-switch v-model="isChinese" @change="toggleLanguage" active-text="中文" inactive-text="English" :disabled=this.isquque||this.isloading||this.isrun></el-switch>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8"><div class="grid-content ">{{ getText('t1pipkine') }}</div></el-col>
          <el-col :span="16">
            <div class="grid-content bg-purple-light">
              <template>
                <el-radio v-model="selectedType" label="type1" @change="saveselectValue" :disabled=canselect>{{ getText('t1raw') }}</el-radio>
                <el-radio v-model="selectedType" label="type2" @change="saveselectValue" :disabled=canselect>{{ getText('t1img') }}</el-radio>
              </template>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <div v-if="false">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="8"><div class="grid-content ">{{ getText('boldpipkine') }}</div></el-col>
            <el-col :span="16">
              <div class="grid-content bg-purple-light">
                <template>
                  <el-radio v-model="selectedType_fun" label="type3" @change="saveselectValue_fun" :disabled=canselect>{{ getText('funraw') }}</el-radio>
                  <el-radio v-model="selectedType_fun" label="type4" @change="saveselectValue_fun" :disabled=canselect>{{ getText('funimg') }}</el-radio>
                </template>
              </div>
            </el-col>
          </el-row>
          <div v-if="this.needfunform">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :disabled=this.isquque||this.isloading||this.isrun>
              <el-row :gutter="50" type="flex" justify="center">
                <el-col :span="12">
                  <el-form-item :label="getText('BOLDTR')" prop="BOLDTR" label-width="150px" class="boldtr-input">
                    <el-input
                      placeholder=""
                      v-model="ruleForm.BOLDTR"
                      clearable>
                      <i slot="suffix" style="font-style:normal;margin-right: 10px;">s</i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="getText('SkipTR')" prop="SkipTR">
                    <el-input
                      placeholder=""
                      v-model.number="ruleForm.SkipTR"
                      clearable>
                      <i slot="suffix" style="font-style:normal;margin-right: 10px;">{{ getText('SkipTRpoint') }}</i>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" type="flex" justify="center">
                <el-col :span="12">
                  <el-form-item :label="getText('SliceOrder')" prop="SliceOrder">
                    <el-input
                      placeholder=""
                      v-model="ruleForm.SliceOrder"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="getText('Refslic')" prop="Refslic">
                    <el-input
                      placeholder=""
                      v-model.number="ruleForm.Refslic"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" type="flex" justify="center">
                <el-col :span="12">
                  <el-form-item :label="getText('VoxelSize')" prop="VoxelSize">
                    <el-input
                      placeholder=""
                      v-model="ruleForm.VoxelSize"
                      clearable>
                      <i slot="suffix" style="font-style:normal;margin-right: 10px;">mm^3</i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="getText('BoundingBox')" prop="BoundingBox">
                    <el-input
                      placeholder=""
                      v-model="ruleForm.BoundingBox"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20" type="flex" justify="center">
                <el-col :span="12">
                  <el-form-item :label="getText('SmoothFWHM')" prop="SmoothFWHM" class="Smooth-input" label-width="150px">
                    <el-input
                      placeholder=""
                      v-model.number="ruleForm.SmoothFWHM"
                      clearable>
                      <i slot="suffix" style="font-style:normal;margin-right: 10px;">mm</i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="getText('FilterLB')" prop="FilterLB" label-width="120px">
                    <el-input
                      placeholder=""
                      v-model="ruleForm.FilterLB"
                      clearable>
                      <i slot="suffix" style="font-style:normal;margin-right: 10px;">Hz</i>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item :label="getText('FilterHB')" prop="FilterHB" label-width="120px">
                    <el-input
                      placeholder=""
                      v-model="ruleForm.FilterHB"
                      clearable>
                      <i slot="suffix" style="font-style:normal;margin-right: 10px;">Hz</i>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-card>
      </div>
      <el-card>
        <div v-if="selectedType">
          <el-row :gutter="20" type="flex" justify="center">
            <el-col :span="12">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="this.isquque||this.isloading||this.isrun"
                @click="handleBatchDelete"
              >{{ getText('delete') }}</el-button>
            </el-col>
            <el-col :span="12">
              <el-button type="submit" @click="uploadFile"  :disabled=this.isquque||this.isloading||this.isrun
              >{{ getText('upload') }}<i class="el-icon-upload el-icon--right"></i></el-button
              >
            </el-col>
          </el-row>
          <el-row :gutter="20" type="flex" justify="center">
            <el-col>
              <div style="color:#FF0000">{{ getText('note') }}</div >
            </el-col>
          </el-row>
          <el-col :span="12">
            <input type="file" ref="fileInput" @change="handleFileUpload" webkitdirectory style="display: none">
          </el-col>
          <el-table :data="userList" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" :selectable="canSelect2">
            </el-table-column>
            <el-table-column :label="getText('paname')" prop="subname"></el-table-column>
            <el-table-column :label="getText('p_age')" prop="subage">
<!--              readonly="isQueue || isLoading || isRun"-->
              <template slot-scope="scope">
                <el-input placeholder=""
                          :disabled="isSwitchDisabled(scope.row)"
                          v-model="scope.row.subage"
                          :style="{ color : scope.row.textColor }"
                          @change="onAgeChange(scope.row)"
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column
              :label="getText('p_sex')"
              prop="p_sex"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.subsex"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="isSwitchDisabled(scope.row)"
                  active-text="男"
                  inactive-text="女"
                  @change="onSexChange(scope.row)"
                />
              </template>
            </el-table-column>

            <el-table-column :label="getText('operate')" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  :disabled="canhandleDelete(scope.row)"
                >{{ getText('delete') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <el-card>
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="submit" @click.prevent="runmat" :disabled=this.isquque||this.isloading||this.isrun
            >{{ getText('run') }}</el-button
            >
          </el-col>
<!--          <el-col :span="6"><el-button type="primary" icon="el-icon-document-add" @click="saveToFile" :disabled=this.isrun||!this.needfunform||this.isquque||this.isloading>{{ getText('save') }}</el-button></el-col>-->
<!--          <input ref="fileInput1" type="file" accept=".txt" style="display: none" @change="handleFileChange1">-->
<!--          <el-col :span="6"><el-button type="primary" icon="el-icon-document" @click="openFileSelector" :disabled=this.isrun||!this.needfunform||this.isquque||this.isloading>{{ getText('load') }}</el-button></el-col>-->
          <el-col :span="6">
              <el-switch v-model="isClinical" @change="toggleLanguage" active-text="科研" inactive-text="临床" :disabled=this.isquque||this.isloading||this.isrun></el-switch>
<!--            <el-button type="primary" icon="el-icon-document" @click="openFileSelector" :disabled=this.isrun||!this.needfunform||this.isquque||this.isloading>{{ getText('load') }}</el-button>-->
          </el-col>
          <el-col :span="6">
            <el-button type="submit" @click="reinput" :disabled=this.isrun||this.isquque
            >{{ getText('refresh') }}</el-button></el-col>
        </el-row>
      </el-card>
      <div v-if="isquque">
      <el-card>
        <el-row :gutter="20" type="flex" justify="center">
            <el-col :span="6">
              <div>{{getText('isquing')}}{{this.numwait}}{{getText('person')}}</div>
            </el-col>
        </el-row>
      </el-card>
      </div>


<!--      <el-card>
        <el-row :gutter="20" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="danger" @click.prevent="dialogVisible = true" :disabled=true>{{ getText('exit') }}</el-button>
          </el-col>
        </el-row>
      </el-card>-->



      <el-dialog
        :visible.sync="dialogVisible"
        width="30%">
        <span style="font-size: 18px;">{{ getText('confirmexit') }}</span>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">{{ getText('unconfirm') }}</el-button>
    <el-button type="primary" @click="exit">{{ getText('confirm') }}</el-button>
  </span>
      </el-dialog>

    </el-col>
    <el-col :span="10">
      <el-row :gutter="20">
        <el-col span="24">
          <el-card>
            <el-button type="primary" @click="handledownlist">{{ getText('download') }}</el-button>
            <el-table  :data="userList" border stripe @selection-change="handleSelectionChangedownload">
              <el-table-column type="selection" width="55" align="center" :selectable="canSelect3">
              </el-table-column>
              <el-table-column :label="getText('paname')" prop="subname"></el-table-column>
              <el-table-column
                prop="progress"
                :label="getText('progress')"
              >
                <template slot-scope="scope">
                  <el-progress
                    type="line"
                    :stroke-width="15"
                    :percentage="scope.row.progress"
                    :color="blue"
                  ></el-progress>
                </template>
              </el-table-column>
              <el-table-column
                prop="status"
                :label="getText('status')"
              >
                <template slot-scope="scope">
                  <el-input placeholder=""
                            readonly="true"
                            v-model="scope.row.status"
                            :style="{ color : scope.row.textColor }"
                  >
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column :label="getText('operate')" prop="isover">
                <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <el-button
                    type="primary"
                    icon="el-icon-download"
                    size="mini"
                    @click="download(scope.row)"
                    :disabled=candownload(scope.row.isover)
                  ></el-button>
                  <el-button
                    type="primary"
                    icon="el-icon-zoom-in"
                    size="mini"
                    @click="watchnii(scope.row)"
                    :disabled=candownload(scope.row.isover)
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>


            <div v-if="this.isrun" class="center-container"><p>{{ getText('retime') }}: {{ countdown }} {{ getText('min') }}</p></div>
          </el-card>
        </el-col>
      </el-row>
    </el-col>
  </el-row>


</template>

<script>
import axios from "axios";
import { saveAs } from 'file-saver';
import Vue from 'vue';
import {
  batchDeleteSubject,
  Delete, download, downloadreportlist,
  getaskid,
  getuserlist, getxyzlen, progressload, queueload, reinpu, runmat,
  upload,
  uploadcomplex,
  updateAge, updateSex
} from '@/api/ibrain/ibrain'


export default {
  mounted() {
    const isChinese = localStorage.getItem('isChinese_value')
    this.isChinese = isChinese ? JSON.parse(isChinese) : false;
    if(isChinese==null)
      this.toggleLanguage(true);
    else
      this.toggleLanguage(this.isChinese);
  },
  created() {
    this.getaskidanduserlist();
    const selectype = localStorage.getItem('selectype_value')
    this.selectedType = selectype
    const selectype2 = localStorage.getItem('selectype2_value')
    this.selectedType_fun = selectype2
    const needfunform = localStorage.getItem('needfunform')
    this.needfunform = needfunform ? JSON.parse(needfunform) : false;
    const storedFormDataString = localStorage.getItem('ruleForm');
    if (storedFormDataString) {
      const storedFormData = JSON.parse(storedFormDataString);
      Object.assign(this.ruleForm, storedFormData);
    }
  },
  watch: {
    isquque(newwel){
      if(newwel==true){
        this.queueloader();
      }
    },
    isloading(newwel) {
      if(newwel){
        this.runloading();
        this.progressloader();
      }else{
        this.runloading().close();
      }
    },
    selectedType_fun(newval){
      if(newval=="type3"||newval=="type4"){
        localStorage.setItem('needfunform',true);
        this.needfunform=true;
      }
    },
    ruleForm: {
      deep: true,
      handler(newVal) {
        localStorage.setItem('ruleForm', JSON.stringify(newVal));
      }
    }
  },
  computed:{
    rules() {
      return {
        SmoothFWHM:[{ required: this.needfunform, message: this.getText('SmoothFWHM')+" "+this.getText('notnull')},
          { type: 'number', message: this.getText('SmoothFWHM')+" "+this.getText('mustnum')}],
        FilterLB:[{ required: this.needfunform, message: this.getText('FilterLB')+" "+this.getText('notnull')},
          {  message: this.getText('FilterLB')+" "+this.getText('mustnum')}],
        FilterHB:[{ required: this.needfunform, message: this.getText('FilterHB')+" "+this.getText('notnull')},
          {  message: this.getText('FilterHB')+" "+this.getText('mustnum')}],
        VoxelSize:[{required: this.needfunform,validator: this.validateVoxelSize,
          trigger: 'blur'
        }],
        BoundingBox:[{required: this.needfunform,validator: this.validateBoundingBox,
          trigger: 'blur'
        }],
        SliceOrder:[{required: this.needfunform,validator: this.validateSliceOrder,
          trigger: 'blur'
        }],
        Refslic:[{ required: this.needfunform, message: this.getText('Refslic')+" "+this.getText('notnull')},
          { type: 'number', message: this.getText('Refslic')+" "+this.getText('mustnum')}],
        BOLDTR:[{ required: this.needfunform, message: this.getText('BOLDTR')+" "+this.getText('notnull')},
          {  message: this.getText('BOLDTR')+" "+this.getText('mustnum')}],
        SkipTR:[{ required: this.needfunform, message: this.getText('SkipTR')+" "+this.getText('notnull')},
          { type: 'number', message: this.getText('SkipTR')+" "+this.getText('mustnum')}],
      };
    },
    canselect(){
      if(this.userList.length==0||this.userList==null){
        console.log(this.userList)
        return false&&(this.isquque||this.isloading||this.isrun)
      }
      else{
        return true
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      isChinese: false,
      texts: {
        en: {
          p_sex:"sex",
          p_age:"age",
          delete:'delete',
          t1pipkine: 'T1 one key pipeline',
          boldpipkine: 'BOLD one key pipeline',
          changlanuage:'切换语言',
          t1raw:'One key from T1Raw data',
          t1img:'One key from T1Img data',
          funraw:'One key from FunRaw data',
          funimg:'One key from FunImg data',
          BOLDTR:'BOLDTR',
          SkipTR:'SkipTR',
          SkipTRpoint:'ckp',
          SliceOrder:'SliceOrder',
          Refslic:'Refslice',
          VoxelSize:'VoxelSize',
          BoundingBox:'BoundingBox',
          SmoothFWHM:'SmoothFWHM',
          FilterLB:'FilterLB',
          FilterHB:'FilterHB',
          upload:'upload participant folder',
          note:'Note: The data for each participant needs to be stored in separate folders, supporting single or multiple participant uploads.The pipeline only supports the simultaneous computation of either DICOM data or NIfTI data and does not allow a mix of both data types for processing.If you have already uploaded one type of data and wish to upload another type simultaneously, please delete the files of the first data type, switch the processing type, and then upload the second type.',
          paname:'participant name',
          operate:'operate',
          run:'run',
          save:'save parameters',
          load:'load parameters',
          refresh:'refresh page',
          progress:'progress',
          status:'status',
          download:'download report',
          retime:'remaining time',
          min:'minutes',
          notnull:'is not null',
          mustnum:'must be numberic',
          gerror:'formal error',
          checkp:'please check parameters',
          error2:'do not upload the same name subject!',
          sucess:'upload sucessful',
          fail:'upload failed,Please check if the file format is correct!',
          ok:'ok',
          uploadtext:'Uploading files, please wait patiently. Do not close the screen or refresh this page during this stage!!Now uploading is ',
          loadtext:'The initialization for the runtime phase is in progress. This step may take some time, so please be patient. Do not close the screen or refresh this page during this stage!!',
          exit:'interrupt program',
          confirmexit:'confirm termination?',
          confirm:'yes',
          unconfirm:'no',
          person:' subject(s)',
          isquing:'Is queuing,there are '
        },
        zh: {
          p_sex:"性别",
          p_age:"年龄",
          delete:'删除',
          t1pipkine: '一键计算T1数据',
          boldpipkine: '一键计算BOLD数据',
          changlanuage:'Change lanuage',
          t1raw:'DICOM输入',
          t1img:'NIFTI输入',
          funraw:'DICOM输入',
          funimg:'NIFTI输入',
          BOLDTR:'BOLD重复时间',
          SkipTR:'删除前',
          SkipTRpoint:'时间点',
          SliceOrder:'层采集顺序',
          Refslic:'参考层',
          VoxelSize:'体素大小',
          BoundingBox:'边界框',
          SmoothFWHM:'空间平滑半峰全宽',
          FilterLB:'滤波频带下限',
          FilterHB:'滤波频带上限',
          upload:'上传被试文件夹',
          note:'注：每个被试的数据需要存放在单独文件夹，支持单一或者多被试上传。pipline只支持同时计算DICOM数据或者NITIFI数据的一种，不支持两种数据混合计算。如果已上传一种数据，想再同时上传另一种，请删除第一种数据的文件再切换一件计算类型后，上传第二种。',
          paname:'被试姓名',
          operate:'操作',
          run:'运行',
          save:'保存参数',
          load:'加载参数',
          refresh:'重置页面内容',
          progress:'进度',
          status:'状态',
          download:'健康报告下载',
          retime:'预估剩余时间',
          min:'分钟',
          notnull:'不能为空',
          mustnum:'必须为数字',
          gerror:'输入格式错误',
          checkp:'请检查参数',
          error2:'请勿重复上传重名的被试！',
          sucess:'上传成功',
          fail:'上传失败，请检查文件格式是否正确！',
          ok:'确定',
          uploadtext:'上传文件中，请您耐心等待,此阶段请勿关闭屏幕及刷新此页面！！当前上传进度为：',
          loadtext:'运行阶段初始化准备中，此步骤准备时间比较久，请您稍安勿躁，此阶段请勿关闭屏幕及刷新此页面！！',
          exit:'中断程序',
          confirmexit:'确定终止？',
          confirm:'确定',
          unconfirm:'取消',
          person:' 人',
          isquing:'正在排队，前方有'
        }
      },
      needfunform:false,
      ruleForm: {
        SmoothFWHM:null,
        FilterLB:null,
        FilterHB:null,
        VoxelSize:null,
        BoundingBox:null,
        SliceOrder:null,
        Refslic:null,
        BOLDTR:null,
        SkipTR:null,
      },
      isloading:false,
      isquque:false,
      numwait:0,
      isrun:false,
      isover:false,
      taskid:undefined,
      files: null,
      // 获取用户列表的参数对象
      userList: [],
      ids:[],
      idsdownload:[],
      selectedType: false,
      selectedType_fun:false,
      isClinical:false,
      countdown:false ,// 初始倒计时时间
    }
  },
  methods: {
    watchnii(row){
      let id = row.id
      let name = row.subname
      getxyzlen({id,name}).then(res=>{
        let x = res.x
        let y = res.y
        let z = res.z
        this.$router.push({
          // 跳转的路径
          path: '/iBrain/watch',
          // 传递的参数，可以是对象形式
          query: {
            x: x,
            y: y,
            z: z,
            id: id,
            name: name
          }
        });
      })
    },
    getaskidanduserlist(){
      let p = {}
      getaskid(p).then(res => {
        this.isrun = res.isrun;
        this.isover = res.isover;
        this.taskid = res.taskid;
        this.isquque = res.isqueue;
        this.numwait = res.numwait;
        this.isloading = res.isloading;
        let p2 = {taskId:res.taskid}
        getuserlist(p2).then(res2=>{
          this.userList=res2.userList;
          this.countdown = res2.countdown;
        })
        if(res.isqueue==true)
          this.queueloader();
        if(res.isloading==true){
          this.runloading();
          this.progressloader();
        }
        if(res.isrun==true)
          this.progressloader();
      })
    },
    toggleLanguage(isChinese) {
      localStorage.setItem('isChinese_value', isChinese);
      this.isChinese = isChinese;
      Vue.config.lang = isChinese ? 'zh' : 'en';
    },
    getText(key) {
      const language = this.isChinese ? 'zh' : 'en';
      return this.texts[language][key];
    },
    reinput(){
      localStorage.removeItem('isChinese_value')
      localStorage.removeItem('needfunform')
      localStorage.removeItem('selectype_value')
      localStorage.removeItem('selectype2_value')
      localStorage.removeItem("ruleForm")
      reinpu().then(res=>{
        console.log(res)
      })
      window.location.reload();
    },
    //---------------------------------------------------------------------------
    download: function (row) {
      console.log(row)
      let taskid = this.taskid
      let name = row.subname
      download({ taskid ,name}).then(res=>{
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', name+"_report.docx");
        document.body.appendChild(link);
        link.click();
      })
    },
    //---------------------------------------------------------------------------
    candownload: function(isover){
      if (!isover)
        return true
      else
        return false
    },
    saveselectValue(){
      localStorage.setItem('selectype_value', this.selectedType)
    },
    saveselectValue_fun(){
      localStorage.setItem('selectype2_value', this.selectedType_fun)
    },
    uploadLoading() {
      const loading = this.$loading({
        lock: true,
        fullScreen: true,
        text: `${this.getText('uploadtext')} 0%`, // 初始上传进度为 0%
        background: "rgba(255,255,255,0.99)",
      });
      return loading;
    },
    runloading(){
      const loading = this.$loading({
        lock: true,
        fullScreen: true,
        text: this.getText('loadtext'),
        background: "rgba(255,255,255,0.99)"
      })
      return loading;
    },
    async runmat(){
      if(this.userList.length==0||this.userList==null)
        this.$alert('请上传计算需要的文件夹才能运行', '注意', {
          confirmButtonText: '确定',
        });
      else {
        try{
          await new Promise(resolve => setTimeout(resolve, 1000));
          if(this.needfunform){
            let p = {'type1':this.selectedType,'type2':this.selectedType_fun,'isChinese':this.isChinese,'taskid':this.taskid
            ,SliceOrder:this.ruleForm.SliceOrder
              ,VoxelSize:this.ruleForm.VoxelSize
              ,BoundingBox:this.ruleForm.BoundingBox
              ,BOLDTR:this.ruleForm.BOLDTR
              ,SkipTR:this.ruleForm.SkipTR
              ,Refslic:this.ruleForm.Refslic
              ,SmoothFWHM:this.ruleForm.SmoothFWHM
              ,FilterLB:this.ruleForm.FilterLB
              ,FilterHB:this.ruleForm.FilterHB
              ,'ids':this.ids};
            runmat(p).then(res => {
              if(res.error==1){
                this.$notify.error({
                  title: '错误',
                  message: '请至少选择一个被试'
                });
              }
              else{
                this.isrun = res.isrun;
                this.isover = res.isover;
                this.isquque = res.isqueue;
                this.numwait = res.numwait;
                this.isloading = res.isloading;
              }
            }).catch(error=>{
              console.log(error)
            })
          }
          else {
            let p = {'type1':this.selectedType,'type2':this.selectedType_fun,'isChinese':this.isChinese,'isClinical':this.isClinical,'taskid':this.taskid,'ids':this.ids};
            console.log(p)
            runmat(p).then(res => {
              if(res.error==1){
                this.$notify.error({
                  title: '错误',
                  message: '请至少选择一个被试'
                });
              }
              else{
                this.isrun = res.isrun;
                this.isover = res.isover;
                this.isquque = res.isqueue;
                this.numwait = res.numwait;
                this.isloading = res.isloading;
              }
            }).catch(error=>{
              console.log(error)
            })
          }
        }catch (error){
          console.error(error);
        }
      }
    },
    queueloader(){
      let quetimer = setInterval(() => {
        let p = {taskid: this.taskid}
        queueload(p).then(res=>{
          this.isrun = res.isrun;
          this.isover = res.isover;
          this.isquque = res.isqueue;
          this.numwait = res.numwait;
          this.isloading = res.isloading;
          if(res.isloading==true){
            clearInterval(quetimer);
          }
        }).catch(error=>{
          console.log(error)
        })
      }, 10000);
    },
    progressloader(){
      let timer = setInterval(() => {
        let p = {taskId: this.taskid}
        progressload(p).then(res=>{
          this.isrun = res.isrun;
          this.isover = res.isover;
          this.isquque = res.isqueue;
          this.numwait = res.numwait;
          this.isloading = res.isloading;
          this.userList = res.userList;
          this.countdown = res.countdown;
          if(res.isover==true){
            clearInterval(timer);
          }
        }).catch(error=>{
          console.log(error)
        })
      }, 5000);
    },
    exit() {
      axios.get('/api/exit').then((response)=>{
        console.log(response.data)
        localStorage.removeItem('isChinese_value')
        localStorage.removeItem('needfunform')
        localStorage.removeItem('selectype_value')
        localStorage.removeItem('clin_value')
        localStorage.removeItem('ruleForm')
        window.location.reload();
      }).catch((error)=>{
        console.log(error)
      })
      this.dialogVisible=false
    },
    handleDelete(row) {
      this.$modal.confirm('是否删除？').then(() =>  {
        let p = {id: row.id,taskid:this.taskid,type1:this.selectedType,type2:this.selectedType_fun}
        Delete(p).then(res=>{
          this.getaskidanduserlist();
          this.$modal.msgSuccess("删除成功");
        })
      })
    },
    canhandleDelete(row) {
      if (this.isquque||this.isloading||this.isrun)
        return true
      else{
        if(row.isover)
          return true
        else
          return false
      }
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    handleSelectionChangedownload(selection){
      this.idsdownload = selection.map(item => item.id);
    },
    handledownlist(){
      if(this.idsdownload.length==0){
        this.$alert('请选择至少一个被试'), '', {
          confirmButtonText: '确定',
        };
      }
      else {
        // 显示全局loading界面
        const downloading = this.downloading();

        let p = { ids: this.ids };
        downloadreportlist(p).then((res) => {
          const url = window.URL.createObjectURL(new Blob([res]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'report.zip');
          document.body.appendChild(link);
          link.click();

          downloading.close();
        }).catch(() => {
          // 处理下载失败的情况，也要隐藏loading界面
          downloading.close();
        });
      }
    },
    isSwitchDisabled(row) {
      if(this.isquque||this.isloading||this.isrun)
        return true
      else {
        return row.isover
      }
    },
    canSelect2(row){
      if(this.isquque||this.isloading||this.isrun)
        return false
      else {
        return !row.isover
      }
    },
    canSelect3(row){
      if(this.isquque||this.isloading)
        return false
      else {
        return row.isover
      }
    },

    handleBatchDelete() {
      if(this.ids.length!=0){
        this.$modal.confirm('是否批量删除数据项？').then(() =>  {
          let p = {ids: this.ids,taskid:this.taskid,type1:this.selectedType,type2:this.selectedType_fun}
          batchDeleteSubject(p).then(res => {
            this.getaskidanduserlist();
            this.$modal.msgSuccess("删除成功");
          })
        })
      }
      else {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个被试'
        });
      }
    },
    async handleFileUpload(event) {
      this.files = event.target.files;
      await this.nextStep('ruleForm');
      console.log('Upload completed!');
    },
    uploadFile() {
      this.$refs.fileInput.click();
    },
    uploadsucess() {
      this.$alert(this.getText('sucess'), '', {
        confirmButtonText: this.getText('ok'),
      });
    },
    uploadfail() {
      this.$alert(this.getText('fail'), '', {
        confirmButtonText: this.getText('ok'),
      });
    },
    downloading(){
      const loading = this.$loading({
        lock: true,
        fullScreen: true,
        text: "下载中",
        spinner:"el-icon-loading",
        background: "rgba(0,0,0,0.8)"
      })
      return loading;
    },
/*     async nextStep(formName) {
      if(this.needfunform){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            return new Promise((resolve) => {
              let formData = new FormData();
              for (let i = 0; i < this.files.length; i++) {
                formData.append(`file`, this.files[i]);
              }
              formData.append('type1',this.selectedType);
              formData.append('type2',this.selectedType_fun);
              formData.append('taskid',this.taskid);
              for(let key in this.ruleForm){
                formData.append(key,this.ruleForm[key]);
                console.log(formData.get(key));
              }
              const pageLoading = this.uploadLoading();
              uploadcomplex(formData).then(res => {
                if(res.error=='error'){
                  pageLoading.close();
                  this.uploadfail()
                }
                else if(res.error=='error2'){
                  this.userList = res.userList;
                  pageLoading.close();
                  this.$notify({
                    title: this.getText('error2'),
                    message: '',
                    type: 'warning'
                  });
                }
                else {
                  this.userList = res.userList;
                  pageLoading.close();
                  this.uploadsucess();
                }
              }).catch(error=>{
                pageLoading.close();
                console.log(error);
                this.uploadfail()
              })
              console.log('Complex Next step completed!');
              resolve();
            });
          } else {
            this.$notify({
              title: this.getText('checkp'),
              message: '',
              type: 'warning'
            });
          }
        });
      }
      else{
        return new Promise((resolve) => {
          const formData = new FormData();
          for (let i = 0; i < this.files.length; i++) {
            formData.append(`file`, this.files[i]);
          }
          formData.append('type',this.selectedType);
          formData.append('taskid',this.taskid);
          const pageLoading = this.uploadLoading();
          upload(formData).then(res => {
            if(res.error=='error'){
              pageLoading.close();
              console.log(error);
              this.uploadfail()
            }
            else if(res.error=='error2'){
              this.userList = res.userList;
              pageLoading.close();
              this.$notify({
                title: this.getText('error2'),
                message: '',
                type: 'warning'
              });
            }else {
              this.userList = res.userList;
              pageLoading.close();
              this.uploadsucess();
            }
          }).catch(error=>{
            pageLoading.close();
            console.log(error);
            this.uploadfail()
          })
          console.log('Next step completed!');
          resolve();
        });
      }
    }, */
    async nextStep(formName) {
      if (this.needfunform) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            return new Promise((resolve) => {
              let formData = new FormData();
              for (let i = 0; i < this.files.length; i++) {
                formData.append(`file`, this.files[i]);
              }
              formData.append('type1', this.selectedType);
              formData.append('type2', this.selectedType_fun);
              formData.append('taskid', this.taskid);
              for (let key in this.ruleForm) {
                formData.append(key, this.ruleForm[key]);
              }

              const pageLoading = this.uploadLoading();
              // 监听上传进度
              uploadcomplex(formData, {
                onUploadProgress: (progressEvent) => {
                  if (progressEvent.total > 0) {
                    const progress = Math.round(
                      (progressEvent.loaded / progressEvent.total) * 100
                    );
                    // 动态更新 loading 的文本
                    pageLoading.text = `${this.getText('uploadtext')} ${progress}%`;
                  }
                },
              })
                .then((res) => {
                  if (res.error == 'error') {
                    pageLoading.close();
                    this.uploadfail();
                  } else if (res.error == 'error2') {
                    this.userList = res.userList;
                    pageLoading.close();
                    this.$notify({
                      title: this.getText('error2'),
                      message: '',
                      type: 'warning',
                    });
                  } else {
                    this.userList = res.userList;
                    pageLoading.close();
                    this.uploadsucess();
                  }
                })
                .catch((error) => {
                  pageLoading.close();
                  console.log(error);
                  this.uploadfail();
                });
              resolve();
            });
          } else {
            this.$notify({
              title: this.getText('checkp'),
              message: '',
              type: 'warning',
            });
          }
        });
      } else {
        return new Promise((resolve) => {
          const formData = new FormData();
          for (let i = 0; i < this.files.length; i++) {
            formData.append(`file`, this.files[i]);
          }
          formData.append('type', this.selectedType);
          formData.append('taskid', this.taskid);

          const pageLoading = this.uploadLoading();
          // 监听上传进度
          upload(formData, {
            onUploadProgress: (progressEvent) => {
              if (progressEvent.total > 0) {
                const progress = Math.round(
                  (progressEvent.loaded / progressEvent.total) * 100
                );
                // 动态更新 loading 的文本
                pageLoading.text = `${this.getText('uploadtext')} ${progress}%`;
              }
            },
          })
            .then((res) => {
              if (res.error == 'error') {
                pageLoading.close();
                console.log(error);
                this.uploadfail();
              } else if (res.error == 'error2') {
                this.userList = res.userList;
                pageLoading.close();
                this.$notify({
                  title: this.getText('error2'),
                  message: '',
                  type: 'warning',
                });
              } else {
                this.userList = res.userList;
                pageLoading.close();
                this.uploadsucess();
              }
            })
            .catch((error) => {
              pageLoading.close();
              console.log(error);
              this.uploadfail();
            });
          resolve();
        });
      }
    },
    onAgeChange(row) {
      let p = {'taskSubId':row.id,'subage':row.subage};
      console.log(p)
      updateAge(p).then(res => {
        console.log(res)
      }).catch(error=>{
        console.log('更新失败，请稍后重试')
      })
    },

    onSexChange(row) {
      let p = {'taskSubId':row.id,'subsex':row.subsex};
      console.log(p)
      updateSex(p).then(res => {
        console.log(res)
      }).catch(error=>{
        console.log('更新失败，请稍后重试')
      })
    },


    saveToFile() {
      const dataToSave =
        `${this.ruleForm.SmoothFWHM}
${this.ruleForm.FilterLB}
${this.ruleForm.FilterHB}
${this.ruleForm.VoxelSize}
${this.ruleForm.BoundingBox}
${this.ruleForm.SliceOrder}
${this.ruleForm.Refslic}
${this.ruleForm.BOLDTR}
${this.ruleForm.SkipTR}`;
      const blob = new Blob([dataToSave], { type: 'text/plain;charset=utf-8' });
      if (this.isChinese)
        saveAs(blob, '参数文件.txt');
      else
        saveAs(blob, 'param_file.txt');
    },
    openFileSelector() {
      this.$refs.fileInput1.click(); // 触发文件选择器的点击事件
    },
    handleFileChange1(event) {
      const file = event.target.files[0]; // 获取选择的文件

      const reader = new FileReader(); // 创建 FileReader 对象
      reader.onload = (event) => {
        const fileContent = event.target.result; // 获取文件内容
        this.parseFileContent(fileContent); // 解析文件内容并加载到 data 属性中
      };
      reader.readAsText(file); // 以文本形式读取文件内容
    },
    parseFileContent(content) {
      const lines = content.split('\n'); // 将文件内容按行分割
      // 根据文件内容的格式，提取所需数据并赋值给data的相应属性
      this.ruleForm.SmoothFWHM = parseFloat(lines[0]);
      this.ruleForm.FilterLB = parseFloat(lines[1]);
      this.ruleForm.FilterHB = parseFloat(lines[2]);
      this.ruleForm.VoxelSize = (lines[3]);
      this.ruleForm.BoundingBox = (lines[4]);
      this.ruleForm.SliceOrder = (lines[5]);
      this.ruleForm.Refslic = parseFloat(lines[6]);
      this.ruleForm.BOLDTR = parseFloat(lines[7]);
      this.ruleForm.SkipTR = parseFloat(lines[8]);
    },
    isSliceOrder(str){
      if(this.needfunform){
        const formatRegex = /^(\d+:\d+:\d+)(,\d+:\d+:\d+)*$/;
        const formatRegex2 = /^(\d+\s\d+\s\d+)(\s\d+\s\d+\s\d+)*$/;
        const formatRegex3 = /^(\d+\s)+\d+$/;
        return formatRegex.test(str)||formatRegex2.test(str)||formatRegex3.test(str)
      }
      return true;
    },
    isVoxelSize(str){
      if(this.needfunform){
        const formatRegex = /^\d+\s\d+\s\d+$/;
        return formatRegex.test(str)
      }
      return true;
    },
    isBoundingBox(str){
      if(this.needfunform) {
        const formatRegex = /^(-?\d+)\s(-?\d+)\s(-?\d+);(-?\d+)\s(-?\d+)\s(-?\d+)$/;
        return formatRegex.test(str)
      }
      return true;
    },
    validateSliceOrder(rule, value, callback) {
      if (this.isSliceOrder(value)) {
        callback();
      } else {
        callback(new Error(this.getText('gerror')));
      }
    },
    validateVoxelSize(rule, value, callback) {
      if (this.isVoxelSize(value)) {
        callback();
      } else {
        callback(new Error(this.getText('gerror')));
      }
    },
    validateBoundingBox(rule, value, callback) {
      if (this.isBoundingBox(value)) {
        callback();
      } else {
        callback(new Error(this.getText('gerror')));
      }
    },
  }
}
</script>

<style>
.boldtr-input {
  width: 430px;
}
.Smooth-input {
  width: 430px;
}
.FilterL-input {
  width: 430px;
}
.FilterH-input {
  width: 430px;
}.center-container {
   display: flex;
   justify-content: center;
   align-items: center;
   font-family: 'Arial, sans-serif';
   color: #335099;
 }
</style>
